package com.example.yichuangyun.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.view.GravityCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.FragmentBusinessBinding;
import com.example.yichuangyun.dialog.EditDialog;
import com.example.yichuangyun.dialog.ExamineDialog;
import com.example.yichuangyun.dialog.MyDialog;
import com.example.yichuangyun.dialog.SinglePickerView;
import com.example.yichuangyun.dialog.SortPopupWindow;
import com.example.yichuangyun.dialog.TimePicker;
import com.example.yichuangyun.dialog.TreeDialog;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.business.BusinessDataModel;
import com.example.yichuangyun.model.business.BusinessModel;
import com.example.yichuangyun.model.business.LabelModel;
import com.example.yichuangyun.mvvm.base.BaseFragment;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.mvvm.ui.activity.order.PlaceOrderActivity;
import com.example.yichuangyun.ui.activity.business.AddBusinessActivity;
import com.example.yichuangyun.ui.activity.business.BusinessDetailsActivity;
import com.example.yichuangyun.ui.activity.business.SearchBusinessActivity;
import com.example.yichuangyun.ui.activity.business.SetSharePersonActivity;
import com.example.yichuangyun.ui.adapter.BusinessAdapter;
import com.example.yichuangyun.ui.adapter.LabelAdapter;
import com.example.yichuangyun.ui.adapter.TimeAdapter;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.DateUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.RequestUtils;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.UMengUtil;
import com.example.yichuangyun.utils.producttreelist.ProductNodeModel;
import com.example.yichuangyun.utils.treelist.Node;
import com.example.yichuangyun.utils.treelist.SetShareBean;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 商机
 */
@SuppressLint("NotifyDataSetChanged")
public class BusinessFragment extends BaseFragment<FragmentBusinessBinding, BaseViewModel> implements LabelAdapter.OnLabelItemClickListener {

    private int page = 1;
    private List<BusinessModel> businessData = new ArrayList<>();
    private BusinessAdapter businessAdapter;
    /**
     * 商机类型/商机来源/意向状态/意向强度/商机进展/接听意向/号码状态/面访情况
     */
    private LabelAdapter businessTypeAdapter, businessFromAdapter, ideaStrengthAdapter,
            businessProgressAdapter, faceStatusAdapter, invitationStatusAdapter;
    private TimeAdapter timeAdapter;
    private final List<LabelModel> businessFromData = new ArrayList<>();
    private List<LabelModel> businessTypeData = new ArrayList<>();

    /**
     * 商机类型：0-我创建的  1-部门创建的 2-我跟进的 3-部门跟进的 4-共享给我的 5-共享给部门的
     * 默认是我跟进的
     */
//    private int businessType = 2;
    private int mBusinessType = 2;
    private String businessTypeName = "我跟进的";

    /**
     * 商机状态（10:新入库；20:需跟踪；30:确认意向；40:邀约成功；50:面谈成功；60:签约成功；70:丢单；90:未签约）
     * 意向状态（0:意向弱；1:意向中；2:意向强）
     * 邀约状态（0:未邀约；1:已邀约）
     * 面访情况（0:未面访；1:已面访）
     * 商机来源id
     */
    private Integer businessStatus = 90, intentionIntensity, invitationState, viewState, businessFromId;
    private final List<LabelModel> businessProgressData = new ArrayList<>();
    private final List<LabelModel> invitationStatusData = new ArrayList<>();
    private final List<LabelModel> intentionIntensityData = new ArrayList<>();
    private final List<LabelModel> faceStatusData = new ArrayList<>();
    private final List<LabelModel> timeData = new ArrayList<>();

    /**
     * 排序弹窗
     */
    private SortPopupWindow popupWindow;
    private String sortType = "", orderKey = "";
    /**
     * 废弃状态 1待废弃
     */
    private Integer discardStatus = null;
    /**
     * 拨打的电话号码
     */
    private String mTelNumber, businessId, clientName;
    private String createOrgId, followOrgId;
    private int isDeptCreate, isDeptFollow;
    private boolean isCreatePerson;
    private TreeDialog treeDialog;
    private final List<Node> mDatas = new ArrayList<>();
    private Node chooseNode, createNode, followNode;
    private boolean isFirstRequest = true;
    private MyDialog myDialog;

    private String beginCreateTime, endCreateTime;

    private TimePicker timePicker;
    private boolean isStart;
    private BusinessModel mBusinessModel;
    private EditDialog editDialog;
    private boolean isLostOrder;

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        binding.includeSelect.recyclerViewBusinessType.setLayoutManager(new GridLayoutManager(mContext, 3));
        binding.includeSelect.recyclerViewFrom.setLayoutManager(new GridLayoutManager(mContext, 3));
        binding.includeSelect.recyclerViewIdeaStrength.setLayoutManager(new GridLayoutManager(mContext, 3));
        binding.includeSelect.recyclerViewBusinessProgress.setLayoutManager(new GridLayoutManager(mContext, 3));
        binding.includeSelect.recyclerViewInvitationStatus.setLayoutManager(new GridLayoutManager(mContext, 3));
        binding.includeSelect.recyclerViewFaceStatus.setLayoutManager(new GridLayoutManager(mContext, 3));
        binding.includeSelect.recyclerViewCreateTime.setLayoutManager(new GridLayoutManager(mContext, 3));
        popupWindow = new SortPopupWindow(mContext, true) {
            @Override
            public void confirm(String mSortType, String mOrderKey) {
                UMengUtil.setCountEventId(Constant.SORT_BUSINESS);
                sortType = mSortType;
                orderKey = mOrderKey;
                page = 1;
                getBusinessList(page);
            }
        };
        getBusinessType();
    }

    @Override
    public void lazyLoadData() {
        initDialog();
        initTreeDialog();
        initSelectData();
        getBusinessSource();
        showLoadingDialog();
        getBusinessList(page);
    }

    /**
     * 商机类型
     */
    private void getBusinessType() {
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getBusinessType(), new MyObserver<HttpRespond<List<LabelModel>>>() {
            @Override
            protected void onSuccess(HttpRespond<List<LabelModel>> listHttpRespond) {
                if (listHttpRespond.code == Constant.SUCCESS) {
                    businessTypeData = listHttpRespond.data;
                    for (LabelModel labelModel : businessTypeData) {
                        if (labelModel.getName().equals(mContext.getString(R.string.my_follow))) {
                            labelModel.setSelect(true);
                            binding.includeSelect.llChooseCreatePerson.setVisibility(View.VISIBLE);
                        }
                    }
                    setBusinessTypeAdapter();
                }
            }
        });
    }

    private void setBusinessTypeAdapter() {
        businessTypeAdapter = new LabelAdapter(1, mContext, businessTypeData, this);
        binding.includeSelect.recyclerViewBusinessType.setAdapter(businessTypeAdapter);
    }

    /**
     * 获取商机来源
     */
    private void getBusinessSource() {
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getBusinessSource(""), new MyObserver<HttpRespond<List<ProductNodeModel>>>() {
            @Override
            protected void onSuccess(HttpRespond<List<ProductNodeModel>> listHttpRespond) {
                if (Constant.SUCCESS == listHttpRespond.code) {
                    if (listHttpRespond.data != null) {
                        for (int i = 0; i < listHttpRespond.data.size(); i++) {
                            ProductNodeModel node = listHttpRespond.data.get(i);
                            businessFromData.add(new LabelModel(Integer.parseInt(node.getId()), node.getLabel()));
                            initSourceList(listHttpRespond.data.get(i).getChildren());
                        }
                        if (businessFromData.size() > 9) {
                            binding.includeSelect.tvBusinessFromMore.setVisibility(View.VISIBLE);
                        }
                        List<LabelModel> list = new ArrayList<>(businessFromData);
                        businessFromAdapter.onRefresh(list);
                    }
                }
            }
        });
    }

    private void initSourceList(List<ProductNodeModel> list) {
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                ProductNodeModel node = list.get(i);
                businessFromData.add(new LabelModel(Integer.parseInt(node.getId()), node.getLabel()));
                initSourceList(node.getChildren());
            }
        }
    }

    /**
     * 获取商机列表
     */
    private void getBusinessList(int page) {
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("examine", mBusinessType);
            requestDate.put("site", 0);
            requestDate.put("isSync", 1);
            requestDate.put("tsourceId", businessFromId);
            // 0-我创建的、1-部门创建的、 2-我跟进的、 3-部门跟进的、4-共享给我的、5-共享给部门的
            if (mBusinessType == 0) {
                requestDate.put(isDeptFollow == 1 ? "gdsignDeptId" : "gdSignId", followOrgId);
            } else if (mBusinessType == 2) {
                requestDate.put(isDeptCreate == 1 ? "creatsignDeptId" : "creatSignId", createOrgId);
            } else {
                requestDate.put(isDeptCreate == 1 ? "creatsignDeptId" : "creatSignId", createOrgId);
                requestDate.put(isDeptFollow == 1 ? "gdsignDeptId" : "gdSignId", followOrgId);
            }
            requestDate.put("beginCreateTime", beginCreateTime);
            requestDate.put("endCreateTime", endCreateTime);
            requestDate.put("stepStatus", businessStatus); // 商机状态：100全部、10 新入库、20需跟踪、30确认意向、40邀约成功、50面谈成功 、60签约成功、70丢单、90未签约
            requestDate.put("intentionIntensity", intentionIntensity); // 意向状态（0:意向弱；1:意向中；2:意向强）
            requestDate.put("invitationState", invitationState); // 邀约状态（0:未邀约；1:已邀约）
            requestDate.put("viewState", viewState); // 面访情况（0:未面访；1:已面访）
            requestDate.put("orderKey", orderKey);
            requestDate.put("orderType", sortType); // 升序asc，降序desc
            requestDate.put("discardStatus", discardStatus); // 废弃状态 1待废弃
            requestDate.put("page", page);
            requestDate.put("pageSize", Constant.pageSize);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getBusinessList(requestBody), new MyObserver<HttpRespond<BusinessDataModel>>() {
            @SuppressLint("SetTextI18n")
            @Override
            protected void onSuccess(HttpRespond<BusinessDataModel> businessDataModelHttpRespond) {
                if (businessDataModelHttpRespond.code == Constant.SUCCESS) {
                    if (businessDataModelHttpRespond.data != null && businessDataModelHttpRespond.data.getRecords() != null) {
                        binding.includeTop.tvBusinessCount.setText(businessTypeName + "· " + businessDataModelHttpRespond.data.getTotal());
                        List<BusinessModel> list = businessDataModelHttpRespond.data.getRecords();
                        if (list.size() < Constant.pageSize) {
                            binding.smartRefreshLayout.finishLoadMoreWithNoMoreData();
                        }
                        if (page == 1) {
                            businessData = list;
                            businessAdapter.onRefresh(list);
                            binding.smartRefreshLayout.finishRefresh();
                        } else {
                            businessAdapter.addData(list);
                            binding.smartRefreshLayout.finishLoadMore();
                        }
                    }
                } else {
                    binding.smartRefreshLayout.finishRefresh();
                    binding.smartRefreshLayout.finishLoadMore();
                }
                dismissLoadingDialog();
            }

            @Override
            protected void onFail(Throwable e) {
                super.onFail(e);
                binding.smartRefreshLayout.finishRefresh();
                binding.smartRefreshLayout.finishLoadMore();
                dismissLoadingDialog();
            }
        });
    }

    @Override
    protected void initCtrl() {
        businessAdapter = new BusinessAdapter(mContext, businessData);
        binding.recyclerView.setAdapter(businessAdapter);
        // 商机来源
        businessFromAdapter = new LabelAdapter(3, mContext, businessFromData, this);
        binding.includeSelect.recyclerViewFrom.setAdapter(businessFromAdapter);
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    protected void initClick() {
        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getBusinessList(page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getBusinessList(page);
            }
        });
        binding.includeTop.ivSort.setOnClickListener(v -> popupWindow.showPopupWindow(binding.includeTop.line));
        binding.includeTop.ivSelect.setOnClickListener(v -> binding.drawerLayout.openDrawer(GravityCompat.END));
        binding.includeTop.ivSearch.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                Bundle bundle = new Bundle();
                bundle.putInt(Constant.businessTypeKey, mBusinessType);
                bundle.putInt(Constant.businessStepStatusKey, businessStatus);
                JumpIntent.jump(getActivity(), SearchBusinessActivity.class, bundle);
            }
        });
        binding.includeTop.ivAddBusiness.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                UMengUtil.setCountEventId(Constant.BUSINESS_ADD_BUSINESS);
                JumpIntent.jump(getActivity(), AddBusinessActivity.class);
            }
        });

        binding.includeSelect.tvCreatePerson.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                isCreatePerson = true;
                chooseNode = null;
                treeDialog.reset();
                if (isFirstRequest) {
                    treeDialog.setTitle(mContext.getString(R.string.please_choose_create_person));
                    getTreeData("");
                } else {
                    if (treeDialog != null) {
                        treeDialog.setTitle(mContext.getString(R.string.please_choose_create_person));
                        treeDialog.showDialog();
                    }
                }
            }
        });

        binding.includeSelect.ivDelete.setOnClickListener(v -> {
            chooseNode = null;
            binding.includeSelect.tvCreatePerson.setText("");
            binding.includeSelect.tvCreatePerson.setEnabled(true);
            binding.includeSelect.ivDelete.setVisibility(View.GONE);
            if (treeDialog != null) {
                treeDialog.reset();
            }
        });

        binding.includeSelect.tvFollowPerson.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                isCreatePerson = false;
                chooseNode = null;
                treeDialog.reset();
                if (isFirstRequest) {
                    getTreeData("");
                } else {
                    if (treeDialog != null) {
                        treeDialog.setTitle(mContext.getString(R.string.please_choose_follow_person));
                        treeDialog.showDialog();
                    }
                }
            }
        });

        binding.includeSelect.ivDelete2.setOnClickListener(v -> {
            chooseNode = null;
            binding.includeSelect.tvFollowPerson.setText("");
            binding.includeSelect.tvFollowPerson.setEnabled(true);
            binding.includeSelect.ivDelete2.setVisibility(View.GONE);
            if (treeDialog != null) {
                treeDialog.reset();
            }
        });

        // 商机来源-更多
        binding.includeSelect.tvBusinessFromMore.setOnClickListener(v -> {
            Drawable drawable;
            if (binding.includeSelect.tvBusinessFromMore.getText().toString().equals(mContext.getString(R.string.more))) {
                binding.includeSelect.tvBusinessFromMore.setText(mContext.getString(R.string.no_expand));
                businessFromAdapter.setItemCount(businessFromData.size());
                drawable = ResourcesCompat.getDrawable(getResources(), R.mipmap.icon_up, null);
            } else {
                binding.includeSelect.tvBusinessFromMore.setText(mContext.getString(R.string.more));
                businessFromAdapter.setItemCount(9);
                drawable = ResourcesCompat.getDrawable(getResources(), R.mipmap.icon_down, null);
            }
            binding.includeSelect.tvBusinessFromMore.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
        });

        binding.includeSelect.tvReset.setOnClickListener(v -> {
            businessTypeAdapter.resetData(1);
            businessProgressAdapter.resetData(2);
            businessFromAdapter.resetData(3);
            ideaStrengthAdapter.resetData(4);
            invitationStatusAdapter.resetData(5);
            faceStatusAdapter.resetData(6);
            timeAdapter.resetData();
            beginCreateTime = null;
            endCreateTime = null;
            binding.includeSelect.tvStartDate.setText("");
            binding.includeSelect.tvEndDate.setText("");
            binding.includeSelect.llChooseCreatePerson.setVisibility(View.GONE);
            binding.includeSelect.llIdeaStrength.setVisibility(View.VISIBLE);
            mBusinessType = 2;
            businessTypeName = mContext.getString(R.string.my_follow);
            sortType = "";
            orderKey = "";
            popupWindow.setSort(mBusinessType);
            businessStatus = 90;
            businessFromId = null;
            intentionIntensity = null;
            viewState = null;
            invitationState = null;
            createOrgId = null;
            binding.includeSelect.llChooseCreatePerson.setVisibility(View.VISIBLE);
            binding.includeSelect.tvCreatePerson.setText("");
            binding.includeSelect.tvCreatePerson.setEnabled(true);
            binding.includeSelect.ivDelete.setVisibility(View.GONE);
            followOrgId = null;
            binding.includeSelect.llChooseFollowPerson.setVisibility(View.GONE);
            binding.includeSelect.tvFollowPerson.setText("");
            binding.includeSelect.tvFollowPerson.setEnabled(true);
            binding.includeSelect.ivDelete2.setVisibility(View.GONE);
            chooseNode = null;
            if (treeDialog != null) {
                treeDialog.reset();
            }
        });

        binding.includeSelect.tvConfirm.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                UMengUtil.setCountEventId(Constant.SCREEN_BUSINESS);
                if (!TextUtils.isEmpty(beginCreateTime) && TextUtils.isEmpty(endCreateTime)) {
                    ToastHelper.show(mContext.getString(R.string.please_choose_end_time));
                    return;
                }
                if (!TextUtils.isEmpty(endCreateTime) && TextUtils.isEmpty(beginCreateTime)) {
                    ToastHelper.show(mContext.getString(R.string.please_choose_start_time));
                    return;
                }
                for (LabelModel labelModel : businessTypeData) {
                    if (labelModel.isSelect()) {
                        mBusinessType = labelModel.getSort();
                        businessTypeName = labelModel.getName();
                        break;
                    }
                }

                for (LabelModel labelModel : businessProgressData) {
                    if (labelModel.isSelect()) {
                        businessStatus = labelModel.getNum();
                        break;
                    } else {
                        businessStatus = 100;
                    }
                }

                for (LabelModel labelModel : businessFromData) {
                    if (labelModel.isSelect()) {
                        businessFromId = labelModel.getId();
                        break;
                    } else {
                        businessFromId = null;
                    }
                }
                for (LabelModel labelModel : invitationStatusData) {
                    if (labelModel.isSelect()) {
                        invitationState = labelModel.getNum();
                        break;
                    } else {
                        invitationState = null;
                    }
                }
                for (LabelModel labelModel : intentionIntensityData) {
                    if (labelModel.isSelect()) {
                        intentionIntensity = labelModel.getNum();
                        break;
                    } else {
                        intentionIntensity = null;
                    }
                }
                for (LabelModel labelModel : faceStatusData) {
                    if (labelModel.isSelect()) {
                        viewState = labelModel.getNum();
                        break;
                    } else {
                        viewState = null;
                    }
                }

                if (!TextUtils.isEmpty(binding.includeSelect.tvCreatePerson.getText().toString())) {
                    isDeptCreate = createNode.isChecked() ? createNode.getIsDept() : 0;
                    createOrgId = createNode.isChecked() ? createNode.getOrgId() : null;
                } else {
                    createNode = null;
                    isDeptCreate = 0;
                    createOrgId = null;
                }

                if (!TextUtils.isEmpty(binding.includeSelect.tvFollowPerson.getText().toString())) {
                    isDeptFollow = followNode.isChecked() ? followNode.getIsDept() : 0;
                    followOrgId = followNode.isChecked() ? followNode.getOrgId() : null;
                } else {
                    followNode = null;
                    isDeptFollow = 0;
                    followOrgId = null;
                }

                if (!TextUtils.isEmpty(binding.includeSelect.tvStartDate.getText().toString()) && !TextUtils.isEmpty(binding.includeSelect.tvEndDate.getText().toString())) {
                    beginCreateTime = binding.includeSelect.tvStartDate.getText().toString();
                    endCreateTime = binding.includeSelect.tvEndDate.getText().toString();
                } else {
                    for (LabelModel labelModel : timeData) {
                        if (labelModel.isSelect()) {
                            beginCreateTime = labelModel.getStartTime();
                            endCreateTime = labelModel.getEndTime();
                            break;
                        } else {
                            beginCreateTime = null;
                            endCreateTime = null;
                        }
                    }
                }

                binding.drawerLayout.closeDrawers();
                if (mBusinessType == 0 || mBusinessType == 1) {
                    sortType = "desc";
                    orderKey = "createTime";
                } else {
                    sortType = "";
                    orderKey = "";
                }
                popupWindow.setSort(mBusinessType);
                page = 1;
                businessAdapter.setBusinessType(mBusinessType);
                binding.recyclerView.scrollToPosition(0);
                binding.smartRefreshLayout.autoRefresh();
            }
        });

        businessAdapter.setOnCallListener((telList, id, userName) -> {
            businessId = id;
            clientName = userName;
            if (telList.size() > 1) {
                initSinglePickerView(telList, mContext.getString(R.string.call_num));
            } else if (telList.size() == 1) {
                mTelNumber = telList.get(0);
                RequestUtils.checkCallNum(mContext, mTelNumber, myDialog, 0, true);
            }
        });

        businessAdapter.setOnMoreListener((businessModel, titleData) -> {
            mBusinessModel = businessModel;
            initSinglePickerView(titleData, "");
        });

        binding.includeSelect.tvStartDate.setOnClickListener(view -> {
            isStart = true;
            timePicker.showPickerView();
        });

        binding.includeSelect.tvEndDate.setOnClickListener(view -> {
            isStart = false;
            timePicker.showPickerView();
        });
    }

    @Override
    public void onLabelItemClickListener(int flag, LabelModel model) {
        if (flag == 1) {
            if (!businessTypeName.equals(model.getName())) {
                binding.includeSelect.tvCreatePerson.setText("");
                binding.includeSelect.tvFollowPerson.setText("");
                binding.includeSelect.ivDelete.setVisibility(View.GONE);
                binding.includeSelect.ivDelete2.setVisibility(View.GONE);
                binding.includeSelect.tvCreatePerson.setEnabled(true);
                binding.includeSelect.tvFollowPerson.setEnabled(true);
                if (treeDialog != null) {
                    treeDialog.reset();
                }
            }
            // 0-我创建的、1-部门创建的、 2-我跟进的、 3-部门跟进的、4-共享给我的、5-共享给部门的
            if (model.getSort() == 0 || model.getSort() == 1) {
                for (LabelModel labelModel : businessProgressData) {
                    labelModel.setSelect(false);
                }
                businessProgressData.get(0).setSelect(true);
                businessProgressAdapter.notifyDataSetChanged();
            } else {
                for (LabelModel labelModel : businessProgressData) {
                    labelModel.setSelect(false);
                }
                businessProgressData.get(6).setSelect(true);
                businessProgressAdapter.notifyDataSetChanged();
            }
            if (model.getSort() == 0) {
                binding.includeSelect.llChooseCreatePerson.setVisibility(View.GONE);
                binding.includeSelect.llChooseFollowPerson.setVisibility(View.VISIBLE);
            } else if (model.getSort() == 2) {
                binding.includeSelect.llChooseCreatePerson.setVisibility(View.VISIBLE);
                binding.includeSelect.llChooseFollowPerson.setVisibility(View.GONE);
            } else {
                binding.includeSelect.llChooseCreatePerson.setVisibility(View.VISIBLE);
                binding.includeSelect.llChooseFollowPerson.setVisibility(View.VISIBLE);
            }
        }
    }

    private void initSelectData() {
        // 商机进展
        businessProgressData.add(new LabelModel(mContext.getString(R.string.all), 100, false));
        businessProgressData.add(new LabelModel(mContext.getString(R.string.new_storage), 10, false));
        businessProgressData.add(new LabelModel(mContext.getString(R.string.to_be_tracked), 20, false));
        businessProgressData.add(new LabelModel(mContext.getString(R.string.confirm_intent), 30, false));
        businessProgressData.add(new LabelModel(mContext.getString(R.string.invitation), 40, false));
        businessProgressData.add(new LabelModel(mContext.getString(R.string.interview), 50, false));
        businessProgressData.add(new LabelModel(mContext.getString(R.string.no_sign), 90, true));
        businessProgressData.add(new LabelModel(mContext.getString(R.string.sign_contract), 60, false));
        businessProgressData.add(new LabelModel(mContext.getString(R.string.discard), 80, false));
        businessProgressAdapter = new LabelAdapter(2, mContext, businessProgressData, this);
        binding.includeSelect.recyclerViewBusinessProgress.setAdapter(businessProgressAdapter);

        // 意向状态
        invitationStatusData.add(new LabelModel(mContext.getString(R.string.weak_intention), 0, false));
        invitationStatusData.add(new LabelModel(mContext.getString(R.string.moderate_intention), 1, false));
        invitationStatusData.add(new LabelModel(mContext.getString(R.string.strong_intention), 2, false));
        ideaStrengthAdapter = new LabelAdapter(4, mContext, invitationStatusData, this);
        binding.includeSelect.recyclerViewIdeaStrength.setAdapter(ideaStrengthAdapter);

        // 邀约情况
        intentionIntensityData.add(new LabelModel(mContext.getString(R.string.label_yes), 1, false));
        intentionIntensityData.add(new LabelModel(mContext.getString(R.string.label_no), 0, false));
        invitationStatusAdapter = new LabelAdapter(5, mContext, intentionIntensityData, this);
        binding.includeSelect.recyclerViewInvitationStatus.setAdapter(invitationStatusAdapter);

        // 面访情况
        faceStatusData.add(new LabelModel(mContext.getString(R.string.label_yes), 1, false));
        faceStatusData.add(new LabelModel(mContext.getString(R.string.label_no), 0, false));
        faceStatusAdapter = new LabelAdapter(6, mContext, faceStatusData, this);
        binding.includeSelect.recyclerViewFaceStatus.setAdapter(faceStatusAdapter);

        timeData.add(new LabelModel(mContext.getString(R.string.this_month), false, DateUtil.getFirstDayOfMonth(DateUtil.LONG_DATE_FORMAT), DateUtil.getLastDayOfMonth(DateUtil.LONG_DATE_FORMAT)));
        timeData.add(new LabelModel(mContext.getString(R.string.last_month), false, DateUtil.getFirstDayOfLastMonth(DateUtil.LONG_DATE_FORMAT), DateUtil.getLastDayOfLastMonth(DateUtil.LONG_DATE_FORMAT)));
        timeData.add(new LabelModel(mContext.getString(R.string.this_week), false, DateUtil.getThisWeekTimeIntervalStart(DateUtil.LONG_DATE_FORMAT), DateUtil.getThisWeekTimeIntervalEnd(DateUtil.LONG_DATE_FORMAT)));
        timeData.add(new LabelModel(mContext.getString(R.string.last_week), false, DateUtil.getLastWeekTimeIntervalStart(DateUtil.LONG_DATE_FORMAT), DateUtil.getLastWeekTimeIntervalEnd(DateUtil.LONG_DATE_FORMAT)));
        timeData.add(new LabelModel(mContext.getString(R.string.yesterday), false, DateUtil.befoDay(), DateUtil.befoDay()));
        timeData.add(new LabelModel(mContext.getString(R.string.today), false, DateUtil.getCurrentDay(), DateUtil.getCurrentDay()));

        timeAdapter = new TimeAdapter();
        timeAdapter.submitList(timeData);
        binding.includeSelect.recyclerViewCreateTime.setAdapter(timeAdapter);
        timeAdapter.setOnLabelClickListener(labelModel -> {
            if (labelModel.isSelect()) {
                binding.includeSelect.tvStartDate.setText("");
                binding.includeSelect.tvEndDate.setText("");
            }
        });
    }

    private void initSinglePickerView(List<String> data, String title) {
        SinglePickerView singlePickerView = new SinglePickerView(getActivity(), title, data) {
            @Override
            public void confirm(String label, int position) {
                if (title.equals(mContext.getString(R.string.call_num))) {
                    mTelNumber = label;
                    RequestUtils.checkCallNum(mContext, mTelNumber, myDialog, 0, true);
                } else {
                    if (label.equals(mContext.getString(R.string.create_order))) { // 生成订单
                        Bundle bundle = new Bundle();
                        bundle.putString(Constant.idKey, mBusinessModel.getId());
                        JumpIntent.jump(getActivity(), PlaceOrderActivity.class, bundle);
                    } else if (label.equals(mContext.getString(R.string.lost_order))) { // 丢单
                        checkButtonOrTab(7);
                    } else if (label.equals(mContext.getString(R.string.discard))) { // 废弃
                        isLostOrder = false;
                        editDialog.setContent(mContext.getString(R.string.discard_reason), mContext.getString(R.string.input_discard_reason));
                        editDialog.showDialog();
                    } else if (label.equals(mContext.getString(R.string.discard_examine))) { // 废弃审核
                        discardExamineBusiness();
                    } else {
                        checkButtonOrTab(6);
                    }
                }
            }
        };
        singlePickerView.showSinglePickerView();
    }

    /**
     * 废弃审核
     */
    private void discardExamineBusiness() {
        ExamineDialog examineDialog = new ExamineDialog(mContext) {
            @Override
            public void rightClick(String content, int result) {
                Map<String, Object> map = new HashMap<>();
                map.put("chanceId", mBusinessModel.getId());
                map.put("remark", content);
                map.put("type", result); // 0同意、1拒绝
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(map));
                RetrofitHelper.getInstance().execute(RetrofitHelper.getService().checkDiscardBusiness(requestBody), new MyObserver<HttpRespond<String>>() {
                    @Override
                    protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                        if (stringHttpRespond.code == Constant.SUCCESS) {
                            ToastHelper.show(getString(R.string.discard_examine_success));
                            page = 1;
                            getBusinessList(page);
                        } else {
                            ToastHelper.show(stringHttpRespond.msg);
                        }
                    }
                });
            }
        };
        examineDialog.showDialog();
    }

    private void initDialog() {
        myDialog = new MyDialog(getActivity()) {
            @Override
            public void leftClick() {
                RequestUtils.callNum(mContext, mTelNumber);
                RequestUtils.addFollow(businessId, clientName, mTelNumber);
                Constant.pushBusinessId = businessId;
            }

            @Override
            public void rightClick() {
                RequestUtils.callbackOutbound(mContext, mTelNumber, businessId, clientName);
            }
        };

        timePicker = new TimePicker((Activity) mContext, true) {
            @Override
            public void confirm(String date) {
                if (isStart) {
                    if (!TextUtils.isEmpty(binding.includeSelect.tvEndDate.getText().toString())) {
                        if (DateUtil.getStringToDate(date) > DateUtil.getStringToDate(binding.includeSelect.tvEndDate.getText().toString())) {
                            ToastHelper.show(mContext.getString(R.string.time_hint1));
                            return;
                        }
                    }
                    binding.includeSelect.tvStartDate.setText(date);
                } else {
                    if (!TextUtils.isEmpty(binding.includeSelect.tvStartDate.getText().toString())) {
                        if (DateUtil.getStringToDate(binding.includeSelect.tvStartDate.getText().toString()) > DateUtil.getStringToDate(date)) {
                            ToastHelper.show(mContext.getString(R.string.time_hint2));
                            return;
                        }
                    }
                    binding.includeSelect.tvEndDate.setText(date);
                }
                timeAdapter.resetData();
            }
        };

        editDialog = new EditDialog(getActivity()) {
            @Override
            public void rightClick(String content) {
                if (isLostOrder) { // 丢单
                    JSONObject requestDate = new JSONObject();
                    try {
                        requestDate.put("chanceId", mBusinessModel.getId());
                        requestDate.put("lostRemark", content);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
                    RetrofitHelper.getInstance().execute(RetrofitHelper.getService().lostOrder(requestBody), new MyObserver<HttpRespond<String>>() {
                        @Override
                        protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                            if (stringHttpRespond.code == Constant.SUCCESS) {
                                ToastHelper.show(mContext.getString(R.string.lost_order_success));
                                page = 1;
                                getBusinessList(page);
                            } else {
                                ToastHelper.show(stringHttpRespond.msg);
                            }

                        }
                    });
                } else { // 废弃
                    Map<String, Object> map = new HashMap<>();
                    map.put("attachments", new JsonArray());
                    map.put("chanceId", mBusinessModel.getId());
                    map.put("remark", content);
                    map.put("discardType", 0);
                    map.put("isDept", 0);
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(map));
                    RetrofitHelper.getInstance().execute(RetrofitHelper.getService().discardBusiness(requestBody), new MyObserver<HttpRespond<String>>() {
                        @Override
                        protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                            if (stringHttpRespond.code == Constant.SUCCESS) {
                                ToastHelper.show(mContext.getString(R.string.discard_success));
                                page = 1;
                                getBusinessList(page);
                            } else {
                                ToastHelper.show(stringHttpRespond.msg);
                            }
                        }
                    });
                }
            }
        };
    }

    private void getTreeData(String keyword) {
        showLoadingDialog();
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("keyword", keyword);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getTreeData(requestBody), new MyObserver<SetShareBean>() {
            @Override
            protected void onSuccess(SetShareBean setShareBean) {
                if (setShareBean.getData().getName() != null) {
                    isFirstRequest = false;
                    Node node = setShareBean.getData();
                    mDatas.add(new Node(node.getName(), node.getId(), node.getParentId(),
                            node.getIsDept(), node.getFullId(), node.getJobNumber(), node.getOrgId()));
                    initList(node.getChildren());
                    initList(node.getUserList());
                    if (chooseNode != null) {
                        for (Node mNode : mDatas) {
                            if (mNode.getId().equals(chooseNode.getId())) {
                                mNode.setChecked(true);
                                break;
                            }
                        }
                    }
                }
                treeDialog.refreshData(TextUtils.isEmpty(keyword) ? 1 : 10);
                if (!treeDialog.isShow()) {
                    treeDialog.showDialog();
                }
                dismissLoadingDialog();
            }

            @Override
            protected void onFail(Throwable e) {
                super.onFail(e);
                ToastHelper.show(e.getMessage());
                dismissLoadingDialog();
            }
        });
    }

    private void initTreeDialog() {
        treeDialog = new TreeDialog(getActivity(), mDatas) {
            @Override
            public void confirm(Node node) {
                chooseNode = node;
                if (isCreatePerson) {
                    createNode = node;
                    binding.includeSelect.tvCreatePerson.setText(node.isChecked() ? node.getName() : "");
                    binding.includeSelect.tvCreatePerson.setEnabled(!node.isChecked());
                    binding.includeSelect.ivDelete.setVisibility(node.isChecked() ? View.VISIBLE : View.GONE);
                } else {
                    followNode = node;
                    binding.includeSelect.tvFollowPerson.setText(node.isChecked() ? node.getName() : "");
                    binding.includeSelect.tvFollowPerson.setEnabled(!node.isChecked());
                    binding.includeSelect.ivDelete2.setVisibility(node.isChecked() ? View.VISIBLE : View.GONE);
                }
            }

            @Override
            public void search(String keyword, Node node) {
                getTreeData(keyword);
            }
        };
    }

    private void initList(List<Node> list) {
        if (list == null || list.size() == 0)
            return;
        for (int i = 0; i < list.size(); i++) {
            Node node = list.get(i);
            mDatas.add(new Node(node.getName(), node.getId(), node.getParentId(),
                    node.getIsDept(), node.getFullId(), node.getJobNumber(), node.getOrgId()));
            if (node.getChildren() == null || node.getChildren().size() == 0) {
                initList(node.getUserList());
            } else {
                initList(node.getChildren());
            }
        }
    }

    /**
     * 检测是否有按钮权限
     *
     * @param type 1、跟进记录 2、通话记录 3、订单记录 4、添加跟进 5、编辑信息 6、设置共享人 7、丢单 8、商机详情
     */
    private void checkButtonOrTab(int type) {
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("type", type);
            // 商机类型  0、我创建的 1、部门创建的 2、我跟进的 3、部门跟进的 4、共享给我的 5、共享给部门的
            if (mBusinessType == 0) {
                requestDate.put("businessType", mBusinessModel.getCreateUserId().equals(mBusinessModel.getGdUserId()) ? 2 : mBusinessType);
            } else if (mBusinessType == 1) {
                requestDate.put("businessType", mBusinessModel.getCreateUserId().equals(mBusinessModel.getGdUserId()) ? 3 : mBusinessType);
            } else {
                requestDate.put("businessType", mBusinessType);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().checkButtonOrTab(requestBody), new MyObserver<HttpRespond<Boolean>>() {
            @Override
            protected void onSuccess(HttpRespond<Boolean> booleanHttpRespond) {
                if (Constant.SUCCESS == booleanHttpRespond.code) {
                    switch (type) {
                        case 6:
                            if (booleanHttpRespond.data) {
                                Bundle bundle = new Bundle();
                                bundle.putString(Constant.businessIdKey, mBusinessModel.getId());
                                JumpIntent.jump(getActivity(), SetSharePersonActivity.class, bundle);
                            } else {
                                ToastHelper.show(mContext.getString(R.string.no_set_share_permission));
                            }
                            break;
                        case 7:
                            if (booleanHttpRespond.data) {
                                isLostOrder = true;
                                editDialog.setContent(mContext.getString(R.string.reason_for_losing_order), mContext.getString(R.string.input_reason_for_losing_order));
                                editDialog.showDialog();
                            } else {
                                ToastHelper.show(mContext.getString(R.string.no_lost_order_permission));
                            }
                            break;
                    }
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (eventBusModel.getMsg().equals(Constant.refreshMainBusinessList)) {
                page = 1;
                getBusinessList(page);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
